/**
 * 全部审批
 */
import React from 'react';
import { history, connect } from 'umi'
import { Card, Table } from 'antd';
import cn from 'classnames';
import xss from 'xss';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import TableFilter from '@/components/TableFilter';
import { useUpdateEffect } from 'react-use';
import FormAdvanced from './FormAdvanced';
import styles from './FullApprovalProcess.less';

export const defaultQuery = (query = {}) => {
    const {
        companyCode = '',
        departmentCode = '',
        title = '',
        endTime = '',
        startTime = '',
        status = '',
        templateNameList = [],
        pageNo = 1,
        pageSize = 10,
        orderBy = ''
    } = query;
    return {
        companyCode,
        departmentCode,
        title,
        endTime,
        startTime,
        status,
        templateNameList: typeof templateNameList === 'string' ? [templateNameList] : templateNameList,
        pageNo,
        pageSize,
        orderBy
    };
};
const parseStatus = list =>
    list.map(item => ({
        text: item.dictName,
        value: item.dictValue
    }));

const FullApprovalProcess = props => {
    const { model, route, location, dispatch, loading } = props;
    const { processStatusType, treeSelectDate, fullApprovalProcess, total } = model;
    const { query: urlQuery } = location;

    const [query, setQuery] = React.useState(defaultQuery(urlQuery));

    // 获取审批流程列表，用于申请类型搜索
    const fetchProcess = () => {
        dispatch({
            type: 'fullApprovalProcess/fetchFormData'
        });
    };

    React.useEffect(() => {
        fetchProcess();
    }, []);

    const fetchFlow = payload => {
        dispatch({
            type: 'fullApprovalProcess/fetchFullApproval',
            payload
        });
    };

    const getSortOrder = key => {
        const { orderBy = '' } = urlQuery;
        const [field, order] = orderBy.split('_');
        if (key !== field) {
            return false;
        }
        return order;
    };

    const handleTableChange = async (pagination, filters, sorter) => {
        let statusObj = {
            status: ''
        };
        if (filters && filters.status && filters.status.length > 0) {
            statusObj = {
                status: filters.status[0]
            };
        }
        // 排序 URL 中的标识规则：createTime_ascend
        const { field, order } = sorter;
        let orderObj = {
            orderBy: ''
        };
        if (field && order) {
            orderObj = {
                orderBy: `${field}_${order}`
            };
        }
        const { orderBy, status, ...rest } = query;
        const finalQuery = { ...rest, pageNo: 1, ...statusObj, ...orderObj };
        history.push({ query: finalQuery });
        setQuery(finalQuery);
    };

    const handlePaginationChange = _pagination => {
        const { current, ...rest } = _pagination;
        const finalQuery = { ...query, ...rest, pageNo: current };
        setQuery(finalQuery);
        history.push({ query: finalQuery });
    };

    const handleSearch = value => {
        const finalQuery = { ...query, ...value, pageNo: 1 };
        setQuery(finalQuery);
        history.push({ query: finalQuery });
    };

    const handleReset = () => {
        const { orderBy, status } = query;
        history.push({ query: { orderBy, status } });
        setQuery({ ...defaultQuery(), orderBy, status });
    };

    const columns = [
        {
            title: '申请主题',
            dataIndex: 'applicationName',
            key: 'applicationName',
            width: '20%',
            render: (text, record) => {
                const { applicationNo } = record;
                const isOldFlow = !applicationNo.includes('-');
                const url = isOldFlow
                    ? '/office/institutions/flowManage/fullApprovalProcess/processDetail'
                    : '/personal/portal/myAuditRead/myAuditReadDetail';
                const params = isOldFlow ? { applicationNo, actionShow: 'no' } : { applicationNo };

                return (
                    <a
                        onClick={() => {
                            history.push({
                                pathname: url,
                                query: params
                            });
                        }}
                    >
                        {text}
                    </a>
                );
            }
        },
        {
            title: '申请单摘要',
            dataIndex: 'applicationNote',
            key: 'applicationNote',
            render(text) {
                return (
                    <div className={styles.lineWord}>
                        <span style={{ wordBreak: 'break-all' }} dangerouslySetInnerHTML={{ __html: xss(text) }} />
                    </div>
                );
            }
        },
        {
            title: '发起时间',
            dataIndex: 'startTime',
            key: 'startTime',
            width: '160px',
            sortOrder: getSortOrder('startTime'),
            sorter: (a, b) => a.age - b.age
        },
        {
            title: '行政机构',
            dataIndex: 'companyName',
            key: 'companyName',
            width: '160px'
        },
        {
            title: '组织机构',
            dataIndex: 'departmentName',
            key: 'departmentName',
            width: '160px'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: '15%',
            render: (text, record) => {
                const arr = record.candidateUsers.split('#');

                let html = '';
                let status = '';
                let color = '';
                // 请求获取状态列表,进行匹配渲染
                for (let index = 0; index < processStatusType.length; index += 1) {
                    if (record.status === processStatusType[index].dictValue) {
                        status = processStatusType[index].dictName;
                    }
                }
                // 审批人如果大于2个以上，显示N人+审批状态
                if (arr.length >= 2) {
                    html = `${arr.length}人${status}`;
                } else if (record.candidateUsers === '') {
                    html = `${status}`;
                } else {
                    html = `${record.candidateUsers}-${status}`;
                }
                // 根据审批状态添加dot的颜色class
                // 1 待发送 2审批中 3未通过 4已通过 5已撤销 6已退回
                if (record.status === '1' || record.status === '2') {
                    color = styles.b;
                } else if (record.status === '3' || record.status === '6') {
                    color = styles.c;
                } else if (record.status === '4') {
                    color = styles.a;
                } else if (record.status === '5') {
                    color = styles.d;
                }
                return (
                    <div>
                        <i className={cn(styles.dot, color)}></i>
                        {html}
                    </div>
                );
            },
            filters: parseStatus(processStatusType),
            filteredValue: typeof query.status !== 'undefined' && query.status ? [query.status] : '',
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />
        }
    ];

    // 首次加载表格数据由高级搜索组件主动触发搜索按钮完成, 要不然没法获取到默认值
    useUpdateEffect(() => {
        const { companyCode, departmentCode, ...restQuery } = query;
        fetchFlow({ companyCode, departmentCode, ...restQuery });
    }, [query]);

    return (
        <PageHeaderWrapper>
            <Card bordered={false} className={styles.temp}>
                <FormAdvanced
                    onSearch={handleSearch}
                    onReset={handleReset}
                    route={route}
                    processStatusType={processStatusType}
                    treeSelectDate={treeSelectDate}
                    query={query}
                />
                <Table
                    rowKey="applicationNo"
                    columns={columns}
                    dataSource={fullApprovalProcess}
                    onChange={handleTableChange}
                    loading={loading}
                    pagination={false}
                    style={{
                        tableLayout: 'fixed',
                        wordBreak: 'break-word'
                    }}
                />
                <Pagination
                    total={total}
                    current={Number(query.pageNo)}
                    pageSize={Number(query.pageSize)}
                    onChange={handlePaginationChange}
                    loading={loading}
                />
            </Card>
        </PageHeaderWrapper>
    );
};

export default connect(({ fullApprovalProcess, loading }) => ({
    model: fullApprovalProcess,
    loading: loading.models.fullApprovalProcess
}))(FullApprovalProcess);
